﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AzukiMap.Layer;
using AzukiMap.Map;
using AzukiMap.MapSource;
using AzukiMap.Renderer;
using AzukiMap.Request;
using AzukiMap.Tools;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.Geometries;
using GisSharpBlog.NetTopologySuite.IO;
using Geometry=System.Windows.Media.Geometry;
using Microsoft.Win32;

namespace AzukiMapWPF_Sample
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private MapControl _mapControl;

        public Window1()
        {
            InitializeComponent();
            MapInit();
        }

        private void MapInit()
        {
            _mapControl = new MapControl(MapCanvas)
                              {
                                  //Srid = 2444,      // Japan Plane Rectangular CS II
                                  //Srid = 2451,      // Japan Plane Rectangular CS IX
                                  Srid = 900913,    // Web Mercator
                                  //Srid = 3785,      // Web Mercator
                                  //Srid = 4326,    // WGS84
                              };

            //_mapControl.MoveToExtents(0,0,100000,100000);   // Japan Place Rectangular CS II
            //_mapControl.MoveToExtents(0,0,100000,100000);   // Japan Place Rectangular CS IX
            _mapControl.MoveToExtents(15531295.36, 4039535.70, 15532631.19, 4041175.52); // Web Mercator
            //_mapControl.MoveToExtents(139, 36, 142, 38);    // WGS84
            //_mapControl.MoveToExtents(139.520, 34.0799, 139.532, 34.0921);    // WGS84 miyake
            //SetGSI();
            //SetBingMap();
            //SetSenkyoku();
            //SetKenBoundary();
            //SetMiyakeRoad();
            //SetWMSAero();
            //SetBuilding();
            //SetOPremium();
            //SetOStandard();
            SetRelief();
            //SetYokohamaOld();
            //SetDRM();
            SetMadFlow();
            //SetTestRect();
        }

        private void SetBingMap()
        {
            var bingSource = new BingSource("Virtual Earth");
            bingSource.TileType = BingLayerType.ROAD;
            //veSource.TileType = VirtualEarthLayerType.HYBRID;
            //bingSource.TileType = BingLayerType.AERIAL;
            var veLayer = new BingLayer(bingSource, "Bing");
            veLayer.Visibility = Visibility.Visible;
            veLayer.Opacity = 1.0;
            _mapControl.AddLayerButtom(veLayer);
        }

        private void SetGSI()
        {
            var layer = new GsiLayer("電子国土")
                            {
                                Visibility = Visibility.Visible,
                                Opacity = 1
                            };
            _mapControl.AddLayerButtom(layer);
        }

        private void SetRelief()
        {
            var source = new WMSSource("Relief", 4326)
                             {
                                 RequestUri = "http://anko.azukimap.jp/cgi-bin/relief_4326",
                                 MaxWidth = 2000,
                                 MaxHeight = 2000,
                                 MaxScale = 500000,
                                 Version = WMSVersion.V1_1_1,
                                 Format = RasterFileSourceFormat.JPEG,
                                 Bgcolor = new Color {R = 218, G = 236, B = 246}
                             };
            //source.Layers.Add("relief_4326");
            source.Layers.Add("relief_85");

            var layer = new WMSLayer(source, "Relief")
                            {
                                Opacity = 1.0
                            };
            _mapControl.AddLayerTop(layer);
        }

        private void SetWMSAero()
        {
            var source = new WMSSource("Mlit ortho", 4612)
                             {
                                 RequestUri = "http://orthophoto.mlit.go.jp:8888/wms/service/wmsRasterTileMap",
                                 MaxHeight = 910,
                                 MaxWidth = 910,
                                 MaxScale = 50000,
                                 Version = WMSVersion.V1_3_0,
                                 Format = RasterFileSourceFormat.JPEG,
                                 BBoxLatLonOrder = LatLonOrder.LAT_LON
                             };

            source.Layers.Add("ORTHO");

            var layer = new WMSLayer(source, "Aero 70's (WMS)")
                            {
                                MaxScale = source.MaxScale,
                                Visibility = Visibility.Collapsed
                            };

            _mapControl.AddLayer(layer);
        }

        private void SetMiyakeRoad()
        {
            var source = new PostGisSource(VectorSourceTypes.MultiLineString)
                             {
                                 Name = "road",
                                 Srid = 4301,
                                 DbName = "miyake",
                                 GeometryColumn = "the_geom",
                                 TableName = "road_bl",
                                 GetColumnDataUri = "http://azukimap.jp/amdev/getGeomDataAttr.php"
                             };

            var layer = new PostGisLayer(source, "road");
            /*
            layer.Labels.Add("大分類");
            layer.Labels.Add("小分類");
            layer.ElementMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(layer_ElementMouseLeftButtonDown);
            layer.ElementMouseEnter += new System.Windows.Input.MouseEventHandler(layer_ElementMouseEnter);
            layer.ElementMouseLeave += new System.Windows.Input.MouseEventHandler(layer_ElementMouseLeave);
             */

            _mapControl.AddLayerTop(layer);
        }

        private void SetKenBoundary()
        {
            var source = new PostGisSource(VectorSourceTypes.MultiPolygon)
                             {
                                 Name = "boundary",
                                 Srid = 4326,
                                 DbName = "datapack",
                                 GeometryColumn = "the_geom",
                                 TableName = "gyouseikai",
                                 GetColumnDataUri = "http://azukimap.jp/amdev/getGeomDataAttr.php"
                             };

            var defaultStyle = new VectorStyle
                                   {
                                       StrokeBrush = new SolidColorBrush(Colors.Red) {Opacity = 0.5},
                                       StrokeThickness = 5
                                   };

            var layer = new PostGisLayer(source, "boundary")
                            {
                                Filter = "syurui = '都道府県界'", 
                                DefaultStyle = defaultStyle
                            };

            _mapControl.AddLayerTop(layer);
        }

        private void SetMadFlow()
        {
            var source = new PostGisSource(VectorSourceTypes.MultiPolygon)
                             {
                                 Name = "mad flow",
                                 Srid = 4326,
                                 DbName = "miyake",
                                 GeometryColumn = "the_geom",
                                 TableName = "miyake_madflowp_bl",
                                 GetColumnDataUri = "http://azukimap.jp/amdev/getGeomDataAttr.php",
                             };
            var layer = new PostGisLayer
                            {
                                // TEST
                                PgSource = source,
                                //Name = "mad flow",
                                Cursor = Cursors.AppStarting
                            };

            _mapControl.AddLayerTop(layer);
        }

        private void SetSenkyoku()
        {
            var source = new PostGisSource(VectorSourceTypes.MultiPolygon)
                             {
                                 Name = "senkyoku",
                                 Srid = 4326,
                                 DbName = "e-stat",
                                 GeometryColumn = "the_geom",
                                 TableName = "senkyoku_1m",
                                 GetColumnDataUri = "http://azukimap.jp/amdev/getGeomDataAttr.php"
                             };

            //source.TableName = "census_poly";
            //source.GetColumnDataUri = "http://azukimap.jp:8000/amdev/getGeomDataAttr.php";

            var defaultStyle = new VectorStyle
                                   {
                                       FillBrush = new SolidColorBrush(Colors.White),
                                       StrokeBrush = new SolidColorBrush(Colors.White)
                                                         {
                                                             Opacity = 0.5
                                                         },
                                       StrokeThickness = 2
                                   };
            var layer = new PostGisLayer(source, "選挙区")
                            {
                                DefaultStyle = defaultStyle,
                                //Filter = "senkyoku is null",
                                MaxScale = 100000
                            };

            var colors = new[]
                             {
                                 Colors.Black,
                                 Colors.Blue,
                                 Colors.Brown,
                                 Colors.Cyan,
                                 Colors.DarkGray,
                                 Colors.Gray,
                                 Colors.Green,
                                 Colors.LightGray,
                                 Colors.Magenta,
                                 Colors.Orange,
                                 Colors.Purple,
                                 Colors.Red,
                                 Colors.Yellow,
                                 Colors.Blue,
                                 Colors.Brown,
                                 Colors.Cyan,
                                 Colors.DarkGray,
                                 Colors.Gray,
                                 Colors.Green,
                                 Colors.LightGray,
                                 Colors.Magenta,
                                 Colors.Orange,
                                 Colors.Purple,
                                 Colors.Red,
                                 Colors.Yellow,
                                 Colors.Blue,
                                 Colors.Brown,
                                 Colors.Cyan,
                                 Colors.DarkGray,
                                 Colors.Gray,
                                 Colors.Green,
                                 Colors.LightGray,
                                 Colors.Magenta,
                                 Colors.Orange,
                                 Colors.Purple,
                                 Colors.Red,
                                 Colors.Yellow,
                             };

            for (int i = 1; i <= 25; i++)
            {
                string expressionStr = "number=" + i;
                //string expressionStr = "senkyoku=" + i.ToString();
                var style = new VectorStyle
                                {
                                    FillBrush = new SolidColorBrush(colors[i]),
                                    StrokeThickness = 1,
                                    StrokeBrush = new SolidColorBrush(Colors.Black)
                                };
                var theme = new VectorLayerTheme(expressionStr, style);
                layer.AddTheme(theme);
            }

            layer.Labels.Add("number");
            //layer.Labels.Add("senkyoku");

            //layer.ElementMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(layer_ElementMouseLeftButtonDown);
            //layer.ElementMouseEnter += new System.Windows.Input.MouseEventHandler(layer_ElementMouseEnter);
            //layer.ElementMouseLeave += new System.Windows.Input.MouseEventHandler(layer_ElementMouseLeave);

            _mapControl.AddLayerTop(layer);
        }

        private void layer_ElementMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var id = (int) ((FrameworkElement) sender).Resources["id"];
            //MessageBox.Show(id.ToString());
        }

        private void layer_ElementMouseLeave(object sender, MouseEventArgs e)
        {
            ((Shape) sender).Stroke = new SolidColorBrush(Colors.Black);
            ((Shape) sender).Fill.Opacity = 1;
        }

        private void layer_ElementMouseEnter(object sender, MouseEventArgs e)
        {
            ((Shape) sender).Stroke = new SolidColorBrush(Colors.Yellow);
            ((Shape) sender).Fill.Opacity = 0.5;
        }

        private void SetYokohamaOld()
        {
            var gf = new GeometryFactory();
            var wktReader = new WKTReader();

            var layerS39 = new RasterIndexLayer("Yokohama s39");

            var sourceS39 = new RasterIndexRecord
                                {
                                    RasterIndex = "http://azukimap.jp/yokohama/raster/84-5.png",
                                    Extent = (IPolygon) wktReader.Read(
                                                            @"POLYGON((
		            139.6304340851354 35.44618595903788,
		            139.6662510613415 35.44618595903788,
		            139.6662510613415 35.42484257756843,
		            139.6304340851354 35.42484257756843,
		            139.6304340851354 35.44618595903788
		            ))")
                                };

            layerS39.AddRaster(sourceS39);

            _mapControl.AddLayerButtom(layerS39);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var bmp = new RenderTargetBitmap((int)MapCanvas.ActualWidth, (int)MapCanvas.ActualHeight, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(MapCanvas);

            Clipboard.SetImage(bmp);
        }

        private void OnLoadClicked(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.ShowDialog();

        }
    }
}
